package top.sjydzq.www.controller.Management;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import top.sjydzq.www.POJO.POJOProduct;
import top.sjydzq.www.service.CategoryService;
import top.sjydzq.www.service.ProductService;

import java.util.List;
import java.util.Vector;

@Controller
@RequestMapping("/management/product/")
public class MProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("list")
    public String list(Model model) {
        model.addAttribute("products", productService.selectAll());

        return "Management/Product/list";
    }

    @RequestMapping("remove")
    public String remove(int id) {
        productService.remove(id);

        return "redirect:/management/product/list";
    }

    @RequestMapping("add")
    public String add(Model model) {

        model.addAttribute("categories", categoryService.selectAll());
        model.addAttribute("operation", "add");

        return "Management/Product/edit";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String handleAdd(POJOProduct pojoProduct, Model model) {
        String title;
        List<String> linkNames = new Vector<>();
        List<String> links = new Vector<>();

        if (productService.add(pojoProduct)) {
            title = "添加成功！";
            linkNames.add("继续添加");
            links.add("/management/product/add");
            linkNames.add("查看商品");
            links.add("/management/product/list");
        } else {
            title = "添加失败！";
            linkNames.add("返回添加");
            links.add("/management/product/add");
        }

        model.addAttribute("title", title);
        model.addAttribute("linkNames", linkNames);
        model.addAttribute("links", links);

        return "Management/Result/index";
    }

    @RequestMapping("edit")
    public String edit(int id, Model model) {
        model.addAttribute("product", productService.selectById(id));
        model.addAttribute("categories", categoryService.selectAll());
        model.addAttribute("operation", String.format("edit?id=%d", id));

        return "Management/Product/edit";
    }

    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public String handleEdit(POJOProduct pojoProduct) {
        productService.edit(pojoProduct);

        return "redirect:/management/product/list";
    }
}


